package xyz.xiangyushui.controller.employee;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import xyz.xiangyushui.dao.ConsumptionHistoryDao;
import xyz.xiangyushui.dao.SalesHistoryDao;
import xyz.xiangyushui.dao.commodity.CommodityDao;
import xyz.xiangyushui.dao.user.member.MembershipDao;

/**
 * Servlet implementation class SalePost
 */
@WebServlet("/employee/salePost")
public class SalePost extends HttpServlet {
	private static final long serialVersionUID = 1L;
       private SalesHistoryDao shd;
       private MembershipDao md;
       private CommodityDao cd;
       private ConsumptionHistoryDao chd;
       private final String membershipNotExist="member not exist";
       private final String memberInsuffientBalance="Balance is insuffient";
       private final String invalidCom="invalid input";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SalePost() {
        super();
        shd=new SalesHistoryDao();
        md=new MembershipDao();
        cd=new CommodityDao();
        chd=new ConsumptionHistoryDao();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String membership=request.getParameter("membership");
		String[] commodity=request.getParameterValues("commodity");
		String msg=validater(membership, commodity,request);
		
		if(msg.equals("success")){
			response.sendRedirect(request.getContextPath()+"/employee/sale");
		}else{
			request.setAttribute("failedMsg", msg);
			request.getRequestDispatcher("/employee").forward(request, response);
		}
	}
	
	private String validater(String membership,String[] commodity,HttpServletRequest request){
		if(check(commodity)){
			if(membership!=null){
				if(membership.equals("")){
					return membershipNotExist;
				}else{
					if(md.getMemberCardId(membership)==0){
						return membershipNotExist;
					}
				}
				//会员购买
				double total=cd.totalPrice(commodity);
				double balance=md.getBalance(membership);
				if(total>balance){
					return memberInsuffientBalance;
				}else{
					int discount=10-md.getRatings(membership);
					double pay=total*(discount/10.0);
					//减少余额
					md.changeBalance(membership, 0-pay);
					//积分
					int points=(int) (total/10);
					//增加积分
					md.changePoints(membership, points);
					//增加log
					chd.addHistory(membership, pay,discount);
					
					//增加日销售额
					String today=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
					shd.updateSalesDailyRecord(today,(int)request.getSession(false).getAttribute("storeId") , pay);
					
					LocalDate now=LocalDate.now();
					for(String c:commodity){
						shd.updateSalesMonthlyCommodity(now.getYear(), now.getMonthValue(), c, (int)request.getSession(false).getAttribute("storeId"));
					}
					return "success";
				}
			}else{
				//非会员购买，添加log
				
				double total=cd.totalPrice(commodity);
				String today=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
				shd.updateSalesDailyRecord(today,(int)request.getSession(false).getAttribute("storeId") , total);
				LocalDate now=LocalDate.now();
				for(String c:commodity){
					shd.updateSalesMonthlyCommodity(now.getYear(), now.getMonthValue(), c, (int)request.getSession(false).getAttribute("storeId"));
				}
				return "success";
			}
		}
		return invalidCom;
	}
	
	private boolean check(String[] commodity){
		for(String c:commodity){
			if(c==null||c.equals("")){
				return false;
			}
		}
		return true;
	}

}
